<template>
    <div class="content-panel">
        <base-form :fields="fields" v-model="form" ref="formRef" :readonly="!editing">
        </base-form>
        <div class="text-center">
            <template v-if="!editing">
                <el-button type="primary" @click="startEdit">编辑</el-button>
                <el-button @click="close">关闭</el-button>
            </template>
            <template v-else>
                <el-button type="primary" @click="doSave">保存</el-button>
                <el-button @click="cancel">取消</el-button>
            </template>
        </div>

        <el-dialog v-model="visible" title="计算字段脚本编辑" destroy-on-close>
            <field-script v-model="metadata" ref="scriptRef" :editing="editing" />

            <template #footer>
                <el-button type="primary" @click="saveScript" v-if="editing">确定</el-button>
                <el-button @click="visible = false">{{ editing ? '取消' : '关闭' }}</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
    import https from '@/utils/https'
    import { ElMessage, ElTag, ElLink } from 'element-plus'
    import { h, onMounted } from 'vue'
    import * as _ from 'lodash'
    import fieldScript from './field-script.vue'

    const emits = defineEmits(["close", "change"])
    const props = defineProps({
        item: Object,
        category: Object
    })
    const fields = [
        { label: '分类', prop: 'categoryId', type: 'treeSelect', options: loadCategory, required: true },
        { label: '模型名称', prop: 'name', required: true },
        { label: '离线检测周期', prop: 'offlineDetection', unit: 'S', default: 300, type: 'number', min: 30 },
        { label: '模型备注', prop: 'remark', type: 'textarea' },
        {
            label: '模型属性', prop: 'fields', type: 'editTable', height: '60vh', showIndex: true, fields: [
                { label: '属性编码', prop: 'code', required: true, width: '200px' },
                { label: '属性名称', prop: 'name', width: '200px' },
                { label: '属性类型', prop: 'type', type: 'radioGroup', options: [{ label: '连接属性', value: 0 }, { label: '计算属性', value: 1 }], width: '240px', align: 'center' },
                { label: '计算规则', prop: 'metadata', width: '140px', disabled: (val, row) => row.type == 0, align: 'center', render: ruleRowRender },
                { label: '单位', prop: 'unit', width: '200px' },
                { label: '备注', prop: 'remark' }
            ], default: {
                type: 0,
                metadata: {
                    scriptType: 'ongl',
                    script: ''
                }
            }, required: true
        }
    ]

    const form = ref({
        offlineDetection: 300,
        fields: []
    })
    const formRef = ref()
    const editing = ref(false)
    const bakForm = ref()

    onMounted(() => {
        if (props.item) {
            https.get('/manager/device-model/detail/' + props.item.id).then(resp => {
                form.value = resp
                editing.value = false
            })
        } else {
            editing.value = true
            if (props.category) {
                form.value.categoryId = props.category.id
            }
        }
    })

    function startEdit() {
        bakForm.value = _.cloneDeep(form.value)
        editing.value = true
    }

    function cancel() {
        if (form.value.id) {
            form.value = bakForm.value
            editing.value = false
        } else {
            close()
        }
    }

    function doSave() {
        formRef.value.validate(res => {
            if (!res) {
                return;
            }

            let params = form.value
            let fields = params.fields
            for (var i in fields) {
                var field = fields[i]
                if (!field.code || !field.name) {
                    ElMessage.error('属性编码或名称不能为空')
                    return
                }
            }

            https.post('/manager/device-model/save', form.value).then(resp => {
                ElMessage.success('操作成功')
                form.value = resp
                editing.value = false
                emits('change')
            })
        })
    }

    function loadCategory() {
        return https.get('/manager/device-model-category/tree')
    }

    function close() {
        emits('close')
    }

    // 编辑规则
    const visible = ref(false)
    const editingRow = ref()
    const metadata = ref()
    const scriptRef = ref()
    function ruleRowRender(val, row) {
        return h(ElLink, {
            type: 'primary', onClick: () => {
                editingRow.value = row
                metadata.value = _.cloneDeep(val || {})
                visible.value = true
            }, disabled: row.type == 0
        }, () => editing.value ? '编辑' : '查看')
    }
    function saveScript() {
        scriptRef.value.validate((res) => {
            if (!res) {
                return
            }

            editingRow.value.metadata = metadata.value
            visible.value = false
        })
    }
</script>
